package com.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {

    String[] excludeSuffix;

    @Override public void init(FilterConfig filterConfig) throws ServletException {
        excludeSuffix = filterConfig.getInitParameter("excludeSuffix").split(",", -1);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        int index = requestURI.lastIndexOf(".");
        if (index > -1) {
            String uriSuffix = requestURI.substring(index + 1);
            for (String suffix : excludeSuffix) {
                if (uriSuffix.equals(suffix)) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }

        Object user = request.getSession().getAttribute("user");

        if (requestURI.contains("logout")) {//登出放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (requestURI.contains("login")) {
            if (user != null) {//已经登录，直接重定向到首页
                response.sendRedirect("index");
                return;
            }
            //登录放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (user == null) {//没有进行登录操作 重定向到登录页
            response.sendRedirect("login");
            return;
        }
        //已经登录放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}